<template>
  <a-modal :maskClosable="false"
    :title='title'
    :width='1248'
    :visible='visible'
    :confirmLoading='confirmLoading'
    @ok='handleOk'
    @cancel='handleCancel'
    cancelText='关闭'>

    <a-spin :spinning='confirmLoading'>

      <a-tabs default-active-key='1'>
        <a-tab-pane key='1' tab='基本计划信息'>
          <a-form-model ref='form' v-bind='layout' :model='model' :rules='validatorRules'>
            <a-row>
              <a-col span="12">
                <a-form-model-item label="计划标题" prop="planTitle">
                  <a-input  v-model="model.planTitle"  placeholder="请输入计划标题"/>
                </a-form-model-item>
              </a-col>
              <a-col span="12">
              </a-col>
            </a-row>
            <a-row>
              <a-col span='12'>
                <a-form-model-item label='开始日期' prop='startTime'>
                  <a-date-picker placeholder='请输入日期' format='YYYY-MM-DD' valueFormat='YYYY-MM-DD'  v-model='model.startTime' />
                </a-form-model-item>
              </a-col>
              <a-col span='12'>
                <a-form-model-item label='结束日期' prop='endTime'>
                  <a-date-picker placeholder='请输入日期' format='YYYY-MM-DD' valueFormat='YYYY-MM-DD'
                                  v-model='model.endTime' />
                </a-form-model-item>
              </a-col>
            </a-row>

            <a-row>
              <a-col span='12'>
                <a-form-model-item label='完成执行次数(次/月)' required prop='execCount'>
                  <a-input-number placeholder='请输入完成执行次数(次/月)' v-model='model.execCount'  style='width: 200px'/>
                </a-form-model-item>
              </a-col>
              <a-col span='12'>

              </a-col>
            </a-row>

            <a-row>
              <a-col span='12'>
                <a-form-model-item label='执行人类型' required prop='execType'>
                  <a-radio-group v-model='model.execType' @change='onChange' default-value="1" disabled=""disabled>
                    <a-radio value='0'>
                      社区
                    </a-radio>
                    <a-radio value='1'>
                      内部职工
                    </a-radio>
                  </a-radio-group>
                </a-form-model-item>
              </a-col>
              <a-col span='12'>
                <a-form-model-item label='负责人' required prop='eyName'>
                  <a-input-search placeholder='请输入负责人' v-model='model.eyName' style="width: 200px" enter-button @search="onSearch" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row justify='start'>
              <a-form-item label='计划走访事务' required prop='followUpContent' :label-col='{span: 3 }'
                           :wrapperCol='{span: 20 }'>
                <a-textarea v-model='model.followUpContent' style='height: 300px'></a-textarea>
              </a-form-item>
            </a-row>
          </a-form-model>
        </a-tab-pane>
        <a-tab-pane key='2' tab='服务对像' force-render>
          <a-row :gutter='18'>
            <a-col :span='16'>
              <!-- 查询区域 -->
              <a-form layout='inline' class='j-inline-form'>
                <!-- 固定条件 -->
                <a-form-item label='客户姓名'>
                  <a-input placeholder='请输入客户姓名' v-model='queryParam.realName'></a-input>
                </a-form-item>
                <a-button type='primary' @click='searchQuery' icon='search'>查询</a-button>
                <a-button type='primary' @click='searchReset' icon='reload' style='margin-left: 8px'>重置</a-button>
              </a-form>

              <div class='ant-alert ant-alert-info' style='margin-bottom: 16px;'>
                <i class='anticon anticon-info-circle ant-alert-icon'></i>
                <span style='color:red;font-size: medium' v-if='switchFullscreenDevice'>{{ switchFullscreenTigMsg
                  }}</span>
                已选择 <a style='font-weight: 600'>{{ selectedRowKeys.length }}</a>项
              </div>
              <a-table
                size='middle'
                bordered
                :rowKey='rowKey'
                :columns='columns'
                :dataSource='dataSource'
                :pagination='ipagination'
                :loading='loading'
                :scroll='{ y: 240 }'
                :rowSelection="{selectedRowKeys, onChange: onSelectChange, type: multiple ? 'checkbox':'radio'}"
                :customRow='customRowFn'
                @change='handleTableChange'>
              </a-table>
            </a-col>
            <a-col :span='8'>
              <a-card :title="'已选' + name" :bordered='false' :head-style='{padding:0}' :body-style='{padding:0}'>
                <!-- 查询区域 -->
                <a-table size='middle' :rowKey='rowKey' bordered v-bind='selectedTable'>
              <span slot='action' slot-scope='text, record, index'>
                <a @click='handleDeleteSelected(record, index)'>删除</a>
              </span>
                </a-table>
              </a-card>
            </a-col>
          </a-row>

        </a-tab-pane>
      </a-tabs>

      <employee-dialog ref='employeeModal' @signOk='handleSignChoice'></employee-dialog>
    </a-spin>
  </a-modal>
</template>

<script>
import { httpAction, putAction, getAction, postAction } from '@api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { pushIfNotExist } from '@/utils/util'
import EmployeeDialog from '@views/his/dialog/EmployeeDialog'

export default {
  name: 'hHisInterviewPlanModal',
  mixins: [JeecgListMixin],
  components: {
    EmployeeDialog,
  },
  data() {
    return {
      title: '操作',
      visible: false,
      model: {
        eyName:"",
        eyId:0,
      },
      layout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 14 }
      },
      confirmLoading: false,
      validatorRules: {
        planTitle: [{ required: true, message: '请输入计划标题!' }],
        year: [{ required: true, message: '请输入执行年!' }],
        serviceQty: [{ required: true, message: '请输入服务人数!' }],
        execCount: [{ required: true, message: '请输入执行次数(次/月)!' }],
        execType: [{ required: true, message: '请输入执行人类型!' }],
        eyName: [{ required: true, message: '请输入负责人!' }],
        followUpContent: [{ required: true, message: '请输入计划走访事务!' }]
      },
      url: {
        add: '/ch/interview/plan',
        edit: '/ch/interview/plan',
        list: '/his/patient/list'
      },
      queryParam: { source: '1' },//TerDeviceInfo.busType
      loading: false,
      switchFullscreenDevice: false,
      switchFullscreenTigMsg: '',
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 5,
        pageSizeOptions: ['5', '10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      rowKey: 'patientId',
      multiple: true,
      columns: [
        { title: '长者姓名', align: 'center', dataIndex: 'realName' },
        { title: '性别', align: 'center', width: '20%', dataIndex: 'sex_dictText' },
        { title: '年龄', align: 'center', width: '40%', dataIndex: 'age' }
      ],
      name: '',
      innerValue: [],
      // 已选择列表
      selectedTable: {
        pagination: false,
        scroll: { y: 240 },
        columns: [
          { title: '长者姓名', align: 'center', width: '50%', dataIndex: 'realName' },
          { title: '操作', dataIndex: 'action', align: 'center', width: 60, scopedSlots: { customRender: 'action' } }
        ],
        dataSource: [],
      }
    }
  },
  watch: {
    selectedRowKeys: {
      immediate: true,
      deep: true,
      handler(val) {
        if (this.innerValue) {
          this.innerValue.length = 0
        }
        this.selectedTable.dataSource = val.map(key => {
          for (let data of this.dataSource) {
            if (data[this.rowKey] === key) {
              pushIfNotExist(this.innerValue, data[this.valueKey])
              return data
            }
          }
          for (let data of this.selectedTable.dataSource) {
            if (data[this.rowKey] === key) {
              pushIfNotExist(this.innerValue, data[this.valueKey])
              return data
            }
          }
          console.warn('未找到选择的行信息，key：' + key)
          return {}
        })
      }
    }
  },
  created() {
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
  },
  methods: {
    /** 删除已选择的 */
    handleDeleteSelected(record, index) {
      this.selectedRowKeys.splice(this.selectedRowKeys.indexOf(record[this.rowKey]), 1)
      //update--begin--autor:wangshuai-----date:20200722------for：JSelectBizComponent组件切换页数值问题------
      this.selectedTable.dataSource.splice(this.selectedTable.dataSource.indexOf(record), 1)
      this.innerValue.splice(this.innerValue.indexOf(record[this.valueKey]), 1)
      console.log('this.selectedRowKeys:', this.selectedRowKeys)
      console.log('this.selectedTable.dataSource:', this.selectedTable.dataSource)
      //update--begin--autor:wangshuai-----date:20200722------for：JSelectBizComponent组件切换页数值问题------
    },

    add() {
      this.edit(this.modelDefault)
      var now = new Date()
      var year = now.getFullYear()
      this.model.year = year
      this.model.execType="1"
    },
    edit(record) {
      this.model = Object.assign({}, record)
      this.visible = true
    },
    close() {
      this.$refs.form.clearValidate()
      this.$emit('close')
      this.visible = false
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          this.model.patientIds=this.selectedRowKeys;
          this.model.planType="2"
          httpAction(httpurl, this.model, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
              that.close()
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          })
        } else {
          return false
        }
      })
    },
    handleCancel() {
      this.close()
    },
    onSearch(){
      this.$refs.employeeModal.show()
      this.$refs.employeeModal.disableSubmit = false
    },
    onChange: function(e) {
      //社工
      if (e.target.value == '0') {
        this.$refs.butlerModal.show(false)
        this.$refs.butlerModal.disableSubmit = false
      } else {
        this.$refs.employeeModal.show()
        this.$refs.employeeModal.disableSubmit = false
      }
    },
    handleSignChoice(record) {
      if(this.model.execType=="1"){
        this.model.eyName = record.name
        this.model.eyId = record.id
      }else{
        this.model.eyName = record.name
        this.model.eyId = record.id
      }

    },
    customRowFn(record) {
      return {
        on: {
          click: () => {
            let key = record[this.rowKey]
            if (!this.multiple) {
              this.selectedRowKeys = [key]
              this.selectedTable.dataSource = [record]
            } else {
              let index = this.selectedRowKeys.indexOf(key)
              if (index === -1) {
                this.selectedRowKeys.push(key)
                this.selectedTable.dataSource.push(record)
              } else {
                this.handleDeleteSelected(record, index)
              }
            }
          }
        }
      }
    }
  }
}
</script>

<style scoped>

</style>
